/**
 * 点赞评论
 * @param id
 * @param state
 * @returns {Promise<Model<any, TModelAttributes>>}
 */
const { Chapter, ChapterLike, Comment } = require("../../models");
const { BadRequestError } = require("../../utils/errors");

/**
 * 点赞
 * @param req
 * @returns {Promise<string>}
 */
exports.like = async (req) => {
  try {
    // 当前登录人

    const { chapterId, userId, id } = req.body; //章节ID
    const chapter = await Chapter.findByPk(chapterId);
    if (!chapter) {
      throw new BadRequestError("章节不存在");
    }
    // 检查是否已经点赞
    const chapterLike = await ChapterLike.findOne({
      where: {
        chapterId,
        userId,
        commentId: id,
      },
    });
    const comment = await Comment.findByPk(id);
    if (!chapterLike) {
      await ChapterLike.create({ chapterId, userId, commentId: comment.id });
      await comment.increment("likes", { by: 1 }); // +1
      return "点赞成功.";
    } else {
      await chapterLike.destroy();
      await comment.decrement("likes", { by: 1 }); // -1
      return "取消点赞.";
    }
  } catch (error) {
    throw new Error(error);
  }
};

/**
 * 获取用户点赞列表
 * @param userId
 * @returns {Promise<Model[]>}
 */
exports.userLikeList = async (userId) => {
  try {
    return await ChapterLike.findAll({
      attributes: ["commentId"],
      where: {
        userId,
      },
      raw: true,
    });
  } catch (error) {
    throw new Error(error);
  }
};
